﻿using System;
using System.Web;
using Newtonsoft.Json;
using System.Web.Security;
using Models.Models;

namespace WebApp.Classes
{
    [Serializable]
    public class UserCookie
    {
        public User User { set; get; }

        public UserCookie Get()
        {
            UserCookie result = new UserCookie();

            try 
            {
                var cookie = (User)JsonConvert.DeserializeObject(System.Web.HttpContext.Current.Request.Cookies["User"].Value, typeof(User));

                result.User = cookie;
            }
            catch 
            {
                System.Web.HttpContext.Current.Request.Cookies.Clear();
                System.Web.HttpContext.Current.Response.Cookies.Clear();                
                FormsAuthentication.SignOut();

                //System.Web.HttpContext.Current.Response.Redirect("~/Account/Login");
            }

            return result;
        }
        
        public void Set(User user) 
        {
            HttpCookie cookie = new HttpCookie("User", JsonConvert.SerializeObject(new { UserID = user.UserID, FirstName = user.FirstName, LastName = user.LastName, StoreID = user.StoreID, ppjStoreID = user.ppjStoreID }));
            cookie.Expires = DateTime.Today.AddMonths(12);

            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}